<script setup>
import { ref, getCurrentInstance, onMounted, reactive } from 'vue'
import { ElMessage, dayjs } from 'element-plus'
import * as htmlparser2 from 'htmlparser2'

import utc from 'dayjs/plugin/utc'
import duration from 'dayjs/plugin/duration'
dayjs.extend(utc)
dayjs.extend(duration)

const internalInstance = getCurrentInstance()
let electron = null
if (window.electron) {
  electron = window.electron
}
console.warn(internalInstance)

let columns = ref([])
let tableData = ref([])
let total = ref(0)
let pageIndex = ref(1)
let pageSize = ref(100)
let loading = ref(false)

// 表单查询
let formInline = reactive({
  task_name: '',
  createdAt: dayjs().format('YYYY-MM-DD HH:mm:ss')
})

columns.value.push(
  ...[
    {
      align: 'center',
      width: '100',
      show: true,
      fixed: false,
      prop: 'id',
      label: '订单号'
    },
    {
      align: 'center',
      // width: '150',
      show: true,
      fixed: false,
      prop: 'task_name',
      label: '任务的标题'
    },
    {
      align: 'center',
      width: '150',
      show: true,
      fixed: false,
      prop: 'nickname',
      label: '主播名称'
    },
    {
      align: 'center',
      // width: '220',
      show: true,
      fixed: false,
      prop: 'live_url',
      label: '直播地址'
    },
    {
      align: 'center',
      // width: '100',
      show: true,
      fixed: false,
      prop: 'duration',
      label: '时长'
    },
    {
      align: 'center',
      // width: '150',
      show: true,
      fixed: false,
      prop: 'number',
      label: '人数'
    },
    {
      align: 'center',
      width: '150',
      show: true,
      fixed: false,
      prop: 'room_id',
      label: '直播间Id'
    },
    {
      align: 'center',
      // width: '150',
      show: true,
      fixed: false,
      prop: 'task_status',
      label: '任务状态'
    },
    // {
    //   align: 'center',
    //   width: '200',
    //   show: true,
    //   fixed: false,
    //   prop: 'home',
    //   label: '主播的个人主页地址'
    // },
    {
      align: 'center',
      // width: '150',
      show: true,
      prop: 'start_time',
      label: '任务开始时间'
    },
    {
      align: 'center',
      // width: '150',
      show: true,
      prop: 'end_time',
      label: '任务结束时间'
    },
    {
      align: 'center',
      width: '300',
      show: true,
      fixed: 'right',
      prop: 'operation',
      label: '操作'
    }
  ]
)

/**
 *
 * @returns 获取任务列表
 *
 */
async function getDouYindTaskList(query = {}) {
  loading.value = true
  await new Promise((resolve) => {
    setTimeout(() => {
      resolve(true)
    }, 100)
  })
  //获取当前登录用户信息
  let userInfo = localStorage.getItem('userinfo')
  if (!userInfo) {
    ElMessage({
      type: 'error',
      message: '登录用户信息为空!'
    })
    return
  }
  let createdAt = dayjs().format('YYYY-MM-DD HH:mm:ss')
  let DouYionEquipment = `http://208.87.207.213:38390/DouYinTask/DouYindList?sgin=47CFD0A2EB7EA1DC043F1B91926890E9&status=0%2C1%2C-1&page=${pageIndex.value}&pageNo=${pageSize.value}`
  // const SendData = {}
  if (query['createdAt']) {
    DouYionEquipment += `&createdAt=${query['createdAt']}`
  } else {
    formInline.createdAt = createdAt
    DouYionEquipment += `&createdAt=${createdAt}`
  }
  if (formInline['task_name']) {
    DouYionEquipment += `&task_name=${query['task_name']}`
  }
  if (JSON.parse(userInfo).id) {
    DouYionEquipment += `&account_id=${JSON.parse(userInfo).id}`
  }
  const response_ = await fetch(DouYionEquipment, {
    method: 'GET',
    headers: {
      'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
    },
    body: undefined
  })
  let response = await response_.json()
  localStorage.setItem('DouYinTaskList', JSON.stringify(response.data))
  loading.value = false
  console.warn(response.data)
  total.value = response.data.count
  tableData.value = response.data.rows
}

/**
 *
 * @returns 更新任务列表
 *
 */

async function DouYinTaskUpdate(rowdata, type) {
  loading.value = true
  await new Promise((resolve) => {
    setTimeout(() => {
      resolve(true)
    }, 100)
  })
  let DouYionEquipment = `http://208.87.207.213:38390/DouYinTask/DouYinTaskUpdate?sgin=47CFD0A2EB7EA1DC043F1B91926890E9`
  let SendData = {}
  if (type && type == 'add') {
    SendData['duration'] = parseInt(rowdata['duration']) + 1
    rowdata['duration'] = parseInt(rowdata['duration']) + 1
    // 任务结束时间加一小时
    if (rowdata['end_time']) {
      let endTime = dayjs(rowdata['end_time']).add(1, 'h').format('YYYY-MM-DD HH:mm:ss')
      SendData['end_time'] = endTime
      rowdata['end_time'] = endTime
    }
  }
  if (type && type == 'sub') {
    if (rowdata['duration'] == 1) {
      ElMessage({
        type: 'error',
        message: '时长必须大于1小时!'
      })
      loading.value = false
      return
    }
    SendData['duration'] = parseInt(rowdata['duration']) - 1
    rowdata['duration'] = parseInt(rowdata['duration']) - 1
    // 任务结束时间减去一小时
    if (rowdata['end_time']) {
      let endTime = dayjs(rowdata['end_time']).subtract(1, 'h').format('YYYY-MM-DD HH:mm:ss')
      SendData['end_time'] = endTime
      rowdata['end_time'] = endTime
    }
  }
  if (!rowdata['start_time']) {
    let time2 = dayjs().format('YYYY-MM-DD HH:mm:ss')
    SendData['start_time'] = time2
    rowdata['start_time'] = time2
  }
  if (!rowdata['end_time']) {
    let time = dayjs().add(rowdata.duration, 'h').format('YYYY-MM-DD HH:mm:ss')
    SendData['end_time'] = time
    rowdata['end_time'] = time
  } else {
    let time = dayjs(rowdata['start_time']).add(rowdata.duration, 'h').format('YYYY-MM-DD HH:mm:ss')
    SendData['end_time'] = time
    rowdata['end_time'] = time
  }
  const response_ = await fetch(DouYionEquipment, {
    method: 'POST',
    headers: {
      'content-type': 'application/json; charset=UTF-8'
    },
    body: JSON.stringify(
      Object.assign(
        {
          id: parseInt(rowdata.id),
          task_status: 2
        },
        SendData
      )
    )
  })
  loading.value = false
  let response = await response_.json()
  console.warn(response)
  if (response.code != 200) {
    ElMessage({
      type: 'error',
      message: '操作失败!' + response.msg
    })
    return
  }
}

async function handleCurrentChange(number) {
  console.warn('handleCurrentChange', number)
  pageIndex.value = number
  await getDouYindTaskList()
}

async function _blank_page(url) {
  if (electron) {
    electron.ipcRenderer.send('_blank_page', url)
  }
}

async function AddDouYindTask() {
  // 获取设备账号数量
  await getDevicesAccountList(1)
  drawer.value = true
}

// 表单提交
const onSubmit = async () => {
  console.log('submit!')
  await getDouYindTaskList(formInline)
}

// 新增订单弹框
const drawer = ref(false)
const direction = ref('ltr')

const form = reactive({
  title: '',
  url: '',
  duration2: '',
  count: '',
  nickname: '',
  server: '',
  room_id: '',
  sec_user_id: ''
})

function cancelClick() {
  form.title = ''
  form.url = ''
  form.duration2 = ''
  form.count = ''
  form.nickname = ''
  form.server = ''
  form.room_id = ''
  form.sec_user_id = ''
  drawer.value = false
}

/**
 *
 * @returns 获取账号设备信息列表
 *
 */
const count = ref(0)
const newDevicesAccount = ref([])
async function getDevicesAccountList(pageNo = 1) {
  await new Promise((resolve) => {
    setTimeout(() => {
      resolve(true)
    }, 100)
  })
  let DouYionEquipment = `http://208.87.207.213:38390/DevicesAccount/DevicesAccountList?sgin=47CFD0A2EB7EA1DC043F1B91926890E9&page=1&pageNo=${pageNo}`
  DouYionEquipment += `&status=1`
  const response_ = await fetch(DouYionEquipment, {
    method: 'GET',
    headers: {
      'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
    },
    body: undefined
  })
  let response = await response_.json()
  count.value = response.data.count
  newDevicesAccount.value = response.data.rows
}

async function urlblur() {
  try {
    if (!form.url) {
      return
    }
    new URL(form.url)
    let response_ = await fetch(form.url, {
      method: 'GET',
      body: undefined
    })
    let URL_ = new URL(response_.url)
    let obj = {}
    for (const iterator of URL_.searchParams) {
      obj[iterator[0]] = iterator[1]
    }
    console.warn(obj)
    if (URL_.hostname == 'webcast.amemv.com') {
      let query = URL_.pathname.split('/')
      let room_id_ = query[query.length - 1]
      form.room_id = room_id_
      form.sec_user_id = obj['sec_user_id']
      electron.ipcRenderer.send('dyuser', `https://www.douyin.com/user/${obj['sec_user_id']}`)
      ElMessage({
        type: 'success',
        message: `首页链接数据解析成功！`
      })
    } else {
      let query = URL_.pathname.split('/')
      let sec_user_id = query[query.length - 1]
      form.sec_user_id = sec_user_id
      electron.ipcRenderer.send('dyuser', response_.url)
    }
  } catch (error) {
    ElMessage({
      type: 'error',
      message: '输入的链接不合法!'
    })
  }
}

/**
 *
 * @returns 新增修改账号设备信息
 *
 */
async function DevicesAccountadd(SendData) {
  loading.value = true
  let DouYionEquipment = `http://208.87.207.213:38390/DevicesAccount/DevicesAccountadd`
  const response_ = await fetch(DouYionEquipment, {
    method: 'POST',
    headers: {
      'content-type': 'application/json; charset=UTF-8'
    },
    body: JSON.stringify({
      sgin: '47CFD0A2EB7EA1DC043F1B91926890E9',
      SendData: JSON.stringify(SendData)
    })
  })
  let response = await response_.json()
  console.warn(response)
  loading.value = false
  if (response.code != 200) {
    ElMessage({
      type: 'error',
      message: '初始化数据失败!' + (response.mes || '')
    })
    return
  }
  await getDevicesAccountList()
}

/**
 *
 * 发送接收任务的websocket
 *
 */

let ws_task = null
let wss_connect = ref('')
let onlineUserForAnchor = ref('')
function ws_taskOpen() {
  if (ws_task) {
    ElMessage({
      type: 'warning',
      message: 'websocket处于连接中!'
    })
    return
  }
  ws_task = new WebSocket('ws://127.0.0.1:9898')
  ws_task.onopen = () => {
    console.warn('ws_task-open:', '')
    ElMessage({
      type: 'success',
      message: 'websocket连接成功!'
    })
  }
  ws_task.onmessage = (msg) => {
    console.warn('ws_task-msg:', msg.data)
    try {
      let obj = JSON.parse(msg.data)
      // eslint-disable-next-line no-constant-condition
      if ((obj.cmd = 'sen_wss_num')) {
        wss_connect.value = obj.wss_connect
        // map_wss.value = obj.wss_num
        onlineUserForAnchor.value = obj.onlineUserForAnchor + ''
      }
    } catch (error) {
      console.warn(error)
    }
  }
  ws_task.addEventListener('sen_wss_num', (data) => {
    console.warn(data)
  })
  ws_task.onclose = (close) => {
    console.warn('ws_task-close:', close)
    ws_task = null
    ElMessage({
      type: 'error',
      message: '连接关闭!'
    })
  }
  ws_task.onerror = (error) => {
    console.warn('ws_task-error:', error)
    ws_task = null
  }
}

function ws_taskClose() {
  if (ws_task) {
    ws_task.close()
    return
  }
  ElMessage({
    type: 'error',
    message: '连接已经关闭!'
  })
}

// cmd CreateTask DeleteTask  GetTask FinishTask
function sendTo(message) {
  if (ws_task) {
    ws_task.send(JSON.stringify(message))
    return
  }
  ElMessage({
    type: 'error',
    message: 'websocket服务连接关闭!'
  })
}

/**
 * 添加任务订单
 */
async function addYinTask() {
  let start_time = dayjs().format('YYYY-MM-DD HH:mm:ss')
  let userInfo = localStorage.getItem('userinfo')
  let body = {
    account_id: JSON.parse(userInfo).id,
    task_name: form.title, //任务标题
    room_id: form.room_id, //房间ID
    user_id: '未知', //用户ID
    sec_user_id: form.sec_user_id, //加密用户ID
    nickname: form.nickname, //主播昵称
    duration: form.duration2, //时长
    number: form.count, //数量
    remarks: '订单添加',
    list: '[]',
    task_status: 2,
    live_url: form.url /* 直播链接 */,
    start_time: start_time,
    end_time: dayjs(start_time).add(form.duration2, 'h').format('YYYY-MM-DD HH:mm:ss')
  }
  // 添加任务
  let response_ = await fetch(`http://208.87.207.213:38390/DouYinTask/DouYinTaskadd`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json; charset=utf-8'
    },
    body: JSON.stringify(body)
  })
  let response = await response_.json()
  if (response.code !== 200) {
    ElMessage({
      type: 'error',
      message: response.msg || '订单添加失败，请检查数据'
    })
    return
  }
  await getDevicesAccountList(form.count)
  // for (const iterator of newDevicesAccount.value) {
  //   console.warn(iterator)
  // }
  drawer.value = false
  let tmp = []
  let SendData = []
  await getDevicesAccountList(form.count)
  for (const iterator of newDevicesAccount.value) {
    iterator.status = 2
    SendData.push(iterator)
    let newtime = new Date().getTime()
    let _rticket = newtime
    let ts = parseInt(_rticket / 1000)
    let wss = new URL(iterator.wss)
    wss.searchParams.set('room_id', form.room_id)
    wss.searchParams.set('_rticket', _rticket)
    wss.searchParams.set('ts', ts)
    wss.searchParams.set('rid', form.room_id)
    let prox = iterator.proxyIp.split('==')
    // console.warn(wss.toString())
    tmp.push({
      webSocketUrl: wss.toString(),
      proxy_ip: prox[0] || '',
      auth: prox[1] || ''
    })
  }
  console.warn(tmp)
  sendTo(
    JSON.stringify({
      cmd: 'CreateTask',
      wss_list: tmp,
      start_time: body.start_time,
      end_time: body.end_time
    })
  )
  await DevicesAccountadd(SendData)
  ElMessage({
    type: 'success',
    message: `订单添加成功！`
  })
  cancelClick()
  await getDouYindTaskList()
}

const serverList = ref([])
serverList.value = Array(10)
  .fill(1)
  .map((v, index) => {
    return { value: '127.0.0.1' + ':' + (9898 + index), label: '127.0.0.1' + ':' + (9898 + index) }
  })

onMounted(async () => {
  let DouYinTaskList = localStorage.getItem('DouYinTaskList')
  if (DouYinTaskList) {
    DouYinTaskList = JSON.parse(DouYinTaskList)
    total.value = DouYinTaskList.count
    tableData.value = DouYinTaskList.rows
  } else {
    await getDouYindTaskList()
  }
  // 连接任务服务器
  ws_taskOpen()

  if (electron) {
    electron.ipcRenderer.on('dyuser', (event, data) => {
      // console.warn(data)
      try {
        let info = JSON.parse(data)
        if (info['err_msg']) {
          ElMessage({
            type: 'error',
            message: info['err_msg']
          })
        }
      } catch (error) {
        let flags_ = false
        let flags_number = 0
        let infostr = []
        const parser = new htmlparser2.Parser(
          {
            onattribute(name, value) {
              if (name == 'img' && value == 'PbpHcHqa') {
                // console.warn(name, value)
              }
            },
            onopentag(name, attribs) {
              if (name == 'a' && 'B3AsdZT9' == attribs.class) {
                try {
                  let parms = new URL(attribs.href)
                  let room_id = parms.searchParams.get('room_id')
                  if (room_id) {
                    // console.warn(room_id)
                    form.room_id = room_id
                  }
                } catch (error) {
                  // console.warn(error)
                }
              }
              if (name == 'img' && 'jZ9bChTp' == attribs.class) {
                // console.warn(attribs.src)
              }
            },
            ontext(text) {
              if (text == '直播中') {
                // console.warn(text)
              }
              if (text == '直播已结束') {
                // console.warn(text)
              }
              if (flags_ && flags_number <= 13) {
                ++flags_number
                infostr.push(text)
                console.warn(text)
                // if (flags_number == 2) {
                //   form.nickname = text
                // }
              }
              if (text == '换肤') {
                flags_ = true
              }
            }
          },
          {
            recognizeCDATA: true
          }
        )
        parser.parseComplete(data)
        console.warn(infostr)
        if (!infostr.includes('直播中')) {
          form.nickname = infostr[0]
          ElMessage({
            type: 'error',
            message: '该直播间尚未开播'
          })
        } else {
          form.nickname = infostr[1]
        }
      }
    })
  }
})

/**
 *
 * @returns 输入框
 *
 */
async function countInput(value) {
  console.warn(value)
  if (count.value - value < 0) {
    ElMessage({
      type: 'error',
      message: '最大人数限制:' + count.value
    })
    form.count = 0
  }
}
</script>

<template>
  <div class="container no-drag">
    <div class="search">
      <el-form ref="queryForm" :inline="true" :model="formInline">
        <el-form-item label="任务标题：">
          <el-input v-model="formInline.task_name" placeholder="请输入任务标题" />
        </el-form-item>
        <el-form-item label="任务创建时间：">
          <el-input
            v-model="formInline.createdAt"
            :value="formInline.createdAt"
            type="datetime-local"
            placeholder="请选择时间"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-button
      style="margin-top: 10px; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1)"
      type="primary"
      size="small"
      @click="getDouYindTaskList"
      >更新任务列表</el-button
    >
    <el-button
      style="margin-top: 10px; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1)"
      type="primary"
      size="small"
      @click="AddDouYindTask"
      >添加、新建任务</el-button
    >
    <div class="total_tatistics">
      <!-- <span>选择服务器: <el-input v-model="WebSocketStr" style="width: 250px"></el-input> </span> -->
      <!-- <el-button type="primary" style="margin-left: 5px" @click="ws_taskOpen">连接</el-button>
      <el-button type="danger" @click="ws_taskClose">断开</el-button> -->
    </div>
    <el-table
      ref="table"
      v-loading="loading"
      :data="tableData"
      empty-text="暂无数据"
      border
      row-key="id"
      size="large"
      stripe
      style="width: 100%"
      height="500"
      highlight-current-row
      :header-cell-style="{ background: '#F9F9F9', color: '#606266' }"
    >
      <el-table-column
        v-for="(item, index) in columns"
        :key="index"
        :align="item.align"
        :show-overflow-tooltip="true"
        :prop="item.prop"
        :label="item.label"
        :width="item.width"
        :fixed="item.fixed"
      >
        <template #default="scope">
          <div v-if="item.prop == 'live_url'">
            <el-link type="primary" @click="_blank_page(scope.row[item.prop])">{{
              scope.row[item.prop]
            }}</el-link>
          </div>
          <div v-else-if="item.prop == 'id'">
            {{ scope.$index + 1 }}
          </div>
          <div v-else-if="item.prop == 'task_status'">
            <el-link v-if="scope.row[item.prop] == 1" type="primary">待开始</el-link>
            <el-link v-else type="success">进行中</el-link>
          </div>
          <div v-else-if="item.prop == 'operation'">
            <el-button size="small" type="primary" @click="DouYinTaskUpdate(scope.row)"
              >选择开始任务</el-button
            >
            <el-button size="small" type="danger" @click="DouYinTaskUpdate(scope.row, 'sub')"
              >减1小时</el-button
            >
            <el-button size="small" type="warning" @click="DouYinTaskUpdate(scope.row, 'add')"
              >加1小时</el-button
            >
          </div>
          <div v-else>{{ scope.row[item.prop] }}</div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 合计统计显示 -->
    <div class="total_tatistics">
      <span>总订单数：{{ total || '0' }} </span>
    </div>
    <div class="pagination">
      <el-pagination
        :current-page="pageIndex"
        layout=" prev, pager, next"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        :total="total"
        background
        prev-text="上一页"
        next-text="下一页"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 新增订单 -->
    <el-drawer
      v-model="drawer"
      class="no-drag"
      size="32%"
      :direction="direction"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <template #header>
        <h4>添加订单</h4>
      </template>
      <template #default>
        <div>
          <el-form ref="ruleFormRef" :model="form" label-width="120px">
            <el-form-item label="任务标题：" required>
              <el-input
                v-model="form.title"
                type="text"
                placeholder="请输入直播任务标题"
                autocomplete="off"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item label="主播名称：" required>
              <el-input
                v-model="form.nickname"
                type="text"
                placeholder="请输入主播名称"
                autocomplete="off"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item label="直播链接：" required>
              <el-input
                v-model="form.url"
                type="textarea"
                placeholder="请输入主播的直播间链接"
                autocomplete="off"
                :autosize="{ minRows: 10, maxRows: 20 }"
                clearable
                @blur="urlblur"
              ></el-input>
            </el-form-item>
            <el-form-item label="时长：" required>
              <el-input
                v-model="form.duration2"
                type="number"
                placeholder="请输入时长（小时）"
                autocomplete="off"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item label="人数：" required>
              <el-input
                v-model="form.count"
                type="number"
                placeholder="请输入直播所需要的人数"
                autocomplete="off"
                clearable
                @input="countInput"
              ></el-input>
              <div style="color: red; font-weight: 600; margin-top: 10px">
                当前可用账号设备数量：{{ count - form.count }}
              </div>
            </el-form-item>
            <el-form-item label="选择服务器：" required>
              <el-select v-model="formInline.server" placeholder="请选选择服务器">
                <el-option
                  v-for="(item, index) in serverList"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancelClick">取 消</el-button>
          <el-button type="primary" @click="addYinTask">提交订单</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<style lang="less" scoped>
.el-form-item__label {
  font-size: 12px;
}
.tablebox {
  table tbody {
    display: block;
    height: 200px;
    overflow-y: scroll;
  }

  table thead,
  tbody tr {
    display: table;
    width: 100%;
    table-layout: fixed;
  }

  .left .el-tooltip__popper,
  .right .el-tooltip__popper {
    padding: 8px 10px;
  }
}

.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}

.total_tatistics {
  padding: 12px;
  font-family: auto;
  font-size: 15px;
  font-weight: bold;
}

.pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 19px;
}
</style>
